import 'dart:async';
import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/match/zq_match_event_entity.dart';
import 'package:sports_new/entity/match/zq_match_info_entity.dart';
import 'package:sports_new/entity/match/match_technic_entity.dart';
import 'package:sports_new/entity/match/match_text_live_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/soccer_api.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/match_detail/soccer/zq_live_widget.dart';
import 'package:sports_new/view/match_detail/soccer/zq_milestone_widget.dart';
import 'package:sports_new/view/match_detail/soccer/zq_statistics_widget.dart';
import 'package:sports_new/widgets/rate_circle_widget.dart';

import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/ads_label.dart';

class ZqMatchOutsView extends StatefulWidget {
  const ZqMatchOutsView({super.key, this.info, this.matchId});

  final ZqMatchInfoEntity? info;
  final int? matchId;

  @override
  State<ZqMatchOutsView> createState() => _ZqMatchOutsViewState();
}

mixin _OutsStateMixin on State<ZqMatchOutsView> {
  var subType = 2;
}

const _homeColor = Color(0xFFF53F3F);
const _guestColor = Color(0xFF2766D6);

class _ZqMatchOutsViewState extends State<ZqMatchOutsView>
    with _OutsStateMixin, AutomaticKeepAliveClientMixin {
  // SoccerMatchDetailController contr1 = Get.find();

  ZqMatchInfoEntity? get info => widget.info;
  int? get matchId => widget.matchId;

  @override
  bool get wantKeepAlive => true;

  MatchTechEntity? tech;
  Map<int, TechnicDetail> topDetails = {};
  List<ZqMatchEventEntity> events = [];
  List<MatchLiveTextEntity> texts = [];
  int count = 0;
  late Timer liveTimer = Timer.periodic(const Duration(seconds: 10), (timer) {
    if (info?.state != MatchState.inMatch) {
      return;
    }
    _getTextLive();
    if (timer.tick % 4 == 0) {
      _getEvents();
      _getTechInfo();
    }
  });

  Future _getTechInfo() async {
    final id = matchId;
    if (id == null) {
      return;
    }
    final model = await Utils.tryOrNullf(() async {
      final response = await SoccerApi.getZqMatchTech(id);
      final model = MatchTechEntity.fromJson(response.data['d']);
      // log("model = ${model.toJson()}");
      return model;
    });
    tech = model;
    model?.topDetail?.forEach((element) {
      topDetails[element.kind ?? 0] = element;
    });
    update();
  }

  Future _getEvents() async {
    final id = matchId;
    if (id == null) {
      return;
    }
    final events = await Utils.tryOrNullf(() async {
      final response = await SoccerApi.getZqMatchEvent(id, 1);
      final l = response?.data['d'] as List;
      final events = l.map((e) => ZqMatchEventEntity.fromJson(e)).toList();
      log("get events = ${events.map((e) => "${e.kind}").join(",")}");
      return events;
    });
    this.events = events ?? [];
    if (subType == 1) {
      update();
    }
  }

  Future _getTextLive({bool all = false}) async {
    final mid = matchId;
    if (mid == null) {
      return;
    }
    final getTexts = await Utils.tryOrNullf(() async {
      final id = this.texts.isEmpty ? null : this.texts.first.liveId;
      final response =
          await SoccerApi.getZqMatchTextLive(mid, isAll: all, liveId: id);
      final l = response.data['d'] as List;
      final liveTexts = l.map((e) => MatchLiveTextEntity.fromJson(e)).toList();
      return liveTexts;
    });
    if (all) {
      texts = List.from(getTexts ?? [], growable: true);
    } else if ((getTexts?.length ?? 0) > 0) {
      final lt = getTexts!.last;
      final idx = texts.indexWhere((element) =>
          element.processTime == lt.processTime &&
          element.content == lt.content);
      if (idx == -1) {
        texts.insertAll(0, getTexts);
      } else {
        texts.removeRange(0, idx + 1);
        texts.insertAll(0, getTexts);
      }
    }
    if (subType == 0) {
      update();
    }
  }

  Future<dynamic> doFetchData() async {
    await Future.wait([_getTechInfo(), _getEvents(), _getTextLive(all: true)]);
  }

  @override
  void initState() {
    super.initState();
    doFetchData().then((value) {
      if (texts.isNotEmpty && info?.state == MatchState.inMatch) {
        subType = 0;
      } else if (events.isNotEmpty) {
        subType = 1;
      }
      update();
    });
    liveTimer;
  }

  @override
  void dispose() {
    liveTimer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh.builder(
      onRefresh: () async {
        await doFetchData();
      },
      childBuilder: (ctx, p) => ListView(
        // physics: const ClampingScrollPhysics(),
        physics: p,
        padding: EdgeInsets.zero,
        children: [
          Container(height: 8),
          const AdsLabel(adsTag: "match_zq_赛况",tapType: 'ggw_bsxq_sk'),
          _header(),
          Styles.card(
            margin: const EdgeInsets.symmetric(horizontal: 8),
            padding: const EdgeInsets.only(bottom: 16),
            child: Column(
              children: [
                const SizedBox(height: 16),
                _subBtns(),
                _subWidget(),
              ],
            )
          ),
          Container(height: 50)
        ],
      ),
    );
  }

  _subBtns() {
    return Container(
      color: Colors.white,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 12),
        height: 37,
        decoration: BoxDecoration(
            color: Colours.greyF7, borderRadius: BorderRadius.circular(33.5)),
        child: Stack(
          children: [
            Positioned.fill(child: LayoutBuilder(
              builder: (p0, p1) {
                final maxWidth = p1.maxWidth - 4;
                return Row(
                  children: [
                    const SizedBox(
                      width: 2,
                    ),
                    AnimatedContainer(
                        width: maxWidth / 3 * subType,
                        duration: const Duration(milliseconds: 200)),
                    Styles.card(
                        width: maxWidth / 3,
                        height: 33,
                        radius: 33.5,
                        color: Colours.white)
                  ],
                );
              },
            )),
            Positioned.fill(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ...List.generate(3, (index) {
                    final s = index == subType;
                    return Expanded(
                      child: QkdText(['文字直播', '重要事件', '技术统计'][index],
                        textAlign: TextAlign.center,
                        color: s ? Colours.main : Colours.grey66,
                        fontWeight: s ? FontWeight.w500 : FontWeight.w400
                      ).tap(() {
                        subType = index;
                        update();
                      })
                    );
                  })
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _subWidget() {
    if (subType == 0) {
      return ZqTextLiveWidget(texts: texts, info: info);
    } else if (subType == 1) {
      return ZqMilestoneWidget(events: events, match: info);
    } else if (subType == 2) {
      return ZqStatisticsWidget(tech: tech, info: info);
    }
    return Container();
  }

  Widget _compare(String title, int left, int right, {bool berate = false}) {
    final total = left + right;
    final double rate = total == 0 ? 0.5 : left / total;
    return Column(
      children: [
        const SizedBox(
          height: 20,
        ),
        Row(
          children: [
            SizedBox(
              width: 30,
              child: QkdText(
                berate
                  ? "${(left * 100 / (left + right)).toStringAsFixed(0)}%"
                  : "$left",
                textAlign: TextAlign.center,
                fontSize: 12,fontFamily: "din"
              )
            ),
            SizedBox(
              width: 44,
              height: 44,
              child: RateCircleWidget(
                color1: total == 0 ? Colours.greyEE : _homeColor,
                color2: total == 0 ? Colours.greyEE : _guestColor,
                radius: 22,
                rate: rate,
                width: 5
              ),
            ),
            SizedBox(
              width: 30,
              child: QkdText(
                berate
                    ? "${(right * 100 / (left + right)).toStringAsFixed(0)}%"
                    : "$right",
                textAlign: TextAlign.center,
                fontSize: 12,fontFamily: "din"
              )
            )
          ],
        ),
        QkdText(title, fontSize: 12, color: Colours.grey66).marginOnly(top: 10),
      ],
    );
  }

  Widget col(String img, String text) => Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(img, width: 12, height: 12)
                .sized(width: 12, height: 12),
            const SizedBox(
              height: 14,
            ),
            QkdText(text,
              fontWeight: FontWeight.w500, fontFamily: "din", fontSize: 12
            )
          ],
        ),
      );

  Widget midCompare(String title, int left, int right) {
    final total = left + right;
    double rate = total == 0 ? 0 : left / total;
    const style = TextStyle(
        color: Colours.text, fontSize: 12, fontWeight: FontWeight.w500,fontFamily: "din");
    return Column(
      children: [
        QkdText.style(title,maxLines: 1, style: const TextStyle(fontSize: 12, color: Colours.grey66))
            .marginOnly(bottom: 1),
        Row(
          children: [
            Container(
                alignment: Alignment.center,
                width: 15,
                margin: const EdgeInsets.only(left: 12, right: 8),
                child: QkdText.style(
                  "$left",
                  maxLines: 1,
                  style: style,
                )),
            Expanded(
              child: LinearProgressIndicator(
                  minHeight: 6,
                  value: rate,
                  backgroundColor: total == 0 ? Colours.greyEE : _guestColor,
                  color: _homeColor).rounded(2),
            ),
            Container(
                alignment: Alignment.center,
                width: 15,
                margin: const EdgeInsets.only(left: 8, right: 12),
                child: QkdText.style(
                  "$right",
                  maxLines: 1,
                  style: style,
                ))
          ],
        )
      ],
    );
  }

  Widget _header() {
    final homeShoot1 = int.tryParse(topDetails[4]?.homeData ?? "") ?? 0;
    final gustShoot1 = int.tryParse(topDetails[4]?.guestData ?? "") ?? 0;

    final homeShoot2 = int.tryParse(topDetails[34]?.homeData ?? "") ?? 0;
    final gustShoot2 = int.tryParse(topDetails[34]?.guestData ?? "") ?? 0;

    final homeYellow = int.tryParse(topDetails[11]?.homeData ?? "") ?? 0;
    final guestYellow = int.tryParse(topDetails[11]?.guestData ?? "") ?? 0;
    final homeCorner = int.tryParse(topDetails[6]?.homeData ?? "") ?? 0;
    final guestCorner = int.tryParse(topDetails[6]?.guestData ?? "") ?? 0;
    final homeRed = int.tryParse(topDetails[13]?.homeData ?? "") ?? 0;
    final guestRed = int.tryParse(topDetails[13]?.guestData ?? "") ?? 0;

    return Styles.card(
      // height: 231,
      padding: const EdgeInsets.only(left: 12,right: 12,bottom: 16),
      margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  CachedNetworkImage(imageUrl: info?.baseInfo?.homeLogo ?? "",
                    placeholder: (context, url) => Styles.placeholderIcon())
                    .sized(width: 28,height: 28),
                  const SizedBox(width: 4),
                  QkdText(info?.baseInfo?.homeName ?? "",fontWeight: FontWeight.w500),
                  // Container(color: _homeColor, width: 14, height: 6)
                  //     .marginOnly(left: 5)
                ],
              ),
              Row(
                children: [
                  QkdText(info?.baseInfo?.guestName ?? "",fontWeight: FontWeight.w500),
                  const SizedBox(width: 4),
                  CachedNetworkImage(imageUrl: info?.baseInfo?.guestLogo ?? "",
                    placeholder: (context, url) => Styles.placeholderIcon(),)
                    .sized(width: 28,height: 28)
                ],
              )
            ],
          ).marginOnly(top: 20, bottom: 20),
          Row(
            children: [
              Container(
                width: 88,
                height: 65,
                decoration: BoxDecoration(
                    color: Colours.greyF7,
                    borderRadius: BorderRadius.circular(4)),
                child: Row(
                  children: [
                    col(Utils.getImgPath("home_jiaoqiu.png"), "$homeCorner"),
                    col(Utils.getImgPath("match_icon_huangpai.png"), "$homeYellow"),
                    col(Utils.getImgPath("match_icon_hongpai.png"), "$homeRed")
                  ],
                ),
              ),
              Expanded(
                  child: Column(
                children: [
                  midCompare("射正球门", homeShoot1, gustShoot1),
                  midCompare("射偏球门", homeShoot2, gustShoot2),
                ],
              )),
              Container(
                width: 88,
                height: 65,
                decoration: BoxDecoration(
                    color: Colours.greyF7,
                    borderRadius: BorderRadius.circular(4)),
                child: Row(
                  children: [
                    col(Utils.getImgPath("match_icon_hongpai.png"), "$guestRed"),
                    col(Utils.getImgPath("match_icon_huangpai.png"), "$guestYellow"),
                    col(Utils.getImgPath("guest_jiaoqiu.png"), "$guestCorner")
                  ],
                ),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _compare(
                  topDetails[43]?.technicCn ?? "进攻",
                  int.tryParse(topDetails[43]?.homeData?.replaceAll("%", "") ??
                          "") ??
                      0,
                  int.tryParse(topDetails[43]?.guestData?.replaceAll("%", "") ??
                          "") ??
                      0),
              _compare(
                  topDetails[44]?.technicCn ?? "危险进攻",
                  int.tryParse(topDetails[44]?.homeData?.replaceAll("%", "") ??
                          "") ??
                      0,
                  int.tryParse(topDetails[44]?.guestData?.replaceAll("%", "") ??
                          "") ??
                      0),
              _compare(
                  topDetails[14]?.technicCn ?? "控球率",
                  int.tryParse(topDetails[14]?.homeData?.replaceAll("%", "") ??
                          "") ??
                      0,
                  int.tryParse(topDetails[14]?.guestData?.replaceAll("%", "") ??
                          "") ??
                      0),
            ],
          )
        ],
      ),
    );
  }
}
